
import React, { useEffect, useReducer } from 'react';

// 定义初始状态
const initialState = {
    count: 0,
    text: '',
};

// 定义 reducer 函数
function reducer(state, action) {
    switch (action.type) {
        case 'increment':
            return { ...state, count: state.count + 1 };
        case 'decrement':
            return { ...state, count: state.count - 1 };
        case 'setText':
            return { ...state, text: action.payload };
        default:
            return state;
    }
}

function UseReducer() {
    const [state, dispatch] = useReducer(reducer, initialState);

    useEffect(() => {
        console.log(state, 'state');
        console.log('state状态改变了');
    }, [state]);

    return (
        <div>
            <h1>Counter: {state.count}</h1>
            <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
            <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>

            <h2>Text: {state.text}</h2>
            <input
                type="text"
                value={state.text}
                onChange={(e) => dispatch({ type: 'setText', payload: e.target.value })}
                placeholder="Type something..."
            />
        </div>
    );
}

export default UseReducer;
